<template>
  <div class="charge-report-wrap">
    <div :class="{'display-flex':showMobilePage}" style="position: relative;">
      <FilterInput
        ref="filterTool"
        v-model="filterInput"
        :filter-list="filterList"
        :show-mobile-icon="showMobilePage"
        show-search-btn
        class="FilterTool"
        @handelClick="queryClick"
        @queryEmpty="queryEmpty" />
      <!-- 调整为 ≥封存 不可核销，v3.1.1 -->
      <!-- projectStatus: 0:待提交 1:待初审 2:待复审 3:待确认 4:待封存 5:已封存 -->
      <PlainCreateBtn
        v-if="hasRouteAuth('admin:project:addAccount') && (detailData.projectStatus < 5 ) && list && list.item.writeOffStatus !== 1"
        class="submit-btn"
        @click="addDrawerOpen">添加核销</PlainCreateBtn>
    </div>
    <div class="middle-box">
      <dataDisplay :data-list="displayData" />
    </div>
    <div class="table-list">
      <div v-loading="listLoading" style="min-height: 82px;">
        <el-table
          v-if="list && list.item.list && list.item.list.length"
          ref="resourceTable"
          :data="list && list.item.list ? list.item.list : []"
          max-height="338px"
          class="fb-table"
          row-key="id"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
        >
          <el-table-column label="核销日期" width="100px">
            <template slot-scope="scope">
              <span v-if="scope.row.writeOffTime">{{ scope.row.writeOffTime | parseTime('{y}/{m}/{d}') }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column label="核销金额(元)" align="right" width="140px">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.incomeAmount" :price="scope.row.incomeAmount" />
            </template>
          </el-table-column>
          <el-table-column label="付款人" width="140px">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.paymentUser" />
            </template>
          </el-table-column>
          <el-table-column label="付款方式" width="120px">
            <template slot-scope="scope">
              <ToolTip :content="getPayWay(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="付款账号" min-width="120px">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.paymentAccount" />
            </template>
          </el-table-column>
          <el-table-column label="类型">
            <template slot-scope="scope">
              {{ scope.row.flowType | flowType }}
            </template>
          </el-table-column>
          <el-table-column label="交易单号" width="120px">
            <template slot-scope="scope">
              <div v-if="scope.row.transactionNumber" class="light-word" @click="toFinanceDetail(scope.row)">
                <ToolTip :content="scope.row.transactionNumber"/>
              </div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column label="流水单号" width="120px">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.flowNumber" />
            </template>
          </el-table-column>
          <el-table-column label="到账日期" width="100px">
            <template slot-scope="scope">
              {{ scope.row.arrivalTime | parseTime('{y}/{m}/{d}') }}
            </template>
          </el-table-column>
          <el-table-column label="流水创建人员" width="110px">
            <template slot-scope="scope">
              {{ scope.row.createName || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="核销人员">
            <template slot-scope="scope">
              {{ scope.row.writeOffUser || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="封账状态">
            <template slot-scope="scope">
              <span v-if="scope.row.sealBillType || scope.row.sealBillType === 0">{{ scope.row.sealBillType | setSealBillType }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="撤销核销" width="140" fixed="right">
            <template slot-scope="scope">
              <!-- projectStatus: 0:待提交 1:待初审 2:待复审 3:待确认 4:待封存 5:已封存 -->
              <el-button
                :disabled="!hasRouteAuth('admin:project:addAccount') || (detailData.projectStatus > 4)"
                :loading="cancelLoading"
                type="info"
                size="small"
                class="to-cancel"
                @click="toCancel(scope)"
              >撤销核销</el-button>
            </template>
          </el-table-column>
        </el-table>
        <EmptyPlaceholder v-else />
      </div>
      <el-row type="flex" justify="end" class="pagination-area">
        <el-pagination
          v-if="list && list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="showMobilePage?'total, prev, next, jumper':'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
    </div>
    <WriteOfFinancialFlowDrawer
      ref="writeOfFinancialFlowRef"
      :client-id="detailData.clientId"
      :client-name="detailData.clientName"
      :write-off-amount="writeOffAmount"
      @enterSuccess="enterSuccess" />
  </div>
</template>
<script>
import incomeAmount from '@/assets/chargeOffDetail/incomeAmount.png';
import chargeOffStatus from '@/assets/chargeOffDetail/chargeoff_status.png';
import flowNumber from '@/assets/chargeOffDetail/flowNumber.png';
import transactionNumber from '@/assets/chargeOffDetail/transactionNumber.png';
import EmptyPlaceholder from '@/components/Common/baseComponent/emptyIcon';
import WriteOfFinancialFlowDrawer from '@/components/Common/writeOfFinancialFlow';
import { setVerificationState, setSealBillType, clientStatusFilter } from '@/filters/status';
import { standardFormatNoHour } from '@/filters/date';
import { moneyFilter, bigDataFilter } from '@/filters/number';
import { getChargeReportList } from '@/api/project';
import { getRepealWriteOff } from '@/api/project';
import { getPayOption } from '@/api/select';
import { parseTime } from '@/utils/index';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import { mapState } from 'vuex';

export default {
  name: 'ChargeReport',
  filters: {
    parseTime,
    standardFormatNoHour,
    setSealBillType,
    setVerificationState,
    flowType(val) {
      // 流水类型。0:普通 1:对抵
      let text = '--';
      switch (val) {
        case 0:
          text = '普通';
          break;
        case 1:
          text = '对抵';
          break;
      }
      return text;
    }
  },
  components: { EmptyPlaceholder, dataDisplay, WriteOfFinancialFlowDrawer },
  props: {
    detailData: {
      type: Object,
      default: () => {
        return null;
      }
    }
  },
  data() {
    return {
      incomeAmount,
      chargeOffStatus,
      transactionNumber,
      flowNumber,
      id: '',
      listLoading: false,
      cancelLoading: false,
      list: null,
      filterInput: {},
      perPage: 20,
      page: 1,
      filterList: [
        { keyword: 'payer', name: '付款人', type: 'input', labelWidth: '85px' },
        { keyword: 'payAccount', name: '付款账号', type: 'input', labelWidth: '85px' },
        { keyword: 'trasactionId', name: '交易单号', type: 'input', labelWidth: '85px' },
        { keyword: 'flowId', name: '流水单号', type: 'input', labelWidth: '85px' },
        { keyword: 'flowCreater', name: '流水创建人', type: 'input', labelWidth: '85px' },
        { keyword: 'charger', name: '核销人员', type: 'input', labelWidth: '85px' },
        { keyword: 'payMethod', name: '付款方式', type: 'select', options: [{ value: -1, label: '全部' }] },
        {
          keyword: 'sealStatus', name: '封账状态', type: 'select',
          options: [{ value: -1, label: '全部' }, { value: 0, label: '待封账' }, { value: 2, label: '封账中' }, { value: 1, label: '已封账' }]
        },
        { keyword: 'flowType', name: '类型', type: 'select', labelWidth: '40px', options: [{ value: 0, label: '普通' }, { value: 1, label: '对抵' }] },
        { keyword: 'writeOffTime', labelWidth: '85px', name: '核销日期', type: 'rangeDate', timeType: 'daterange' },
        { keyword: 'arrivalTime', name: '到账日期', type: 'rangeDate', timeType: 'daterange' }
      ],
      rangeKeyArr: [{
        attr: 'writeOffTime',
        start: 'chargeStart',
        end: 'chargeEnd',
        type: 'time'
      }, {
        attr: 'arrivalTime',
        start: 'intoAccountStart',
        end: 'intoAccountEnd',
        type: 'time'
      }]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    writeOffAmount() {
      if (this.list && this.list.item) {
        return this.list.item.unWriteOffAmount;
      } else {
        return 0;
      }
    },
    displayData() {
      if (!this.list || !this.list.item) return [];
      return [
        { data: this.list.item.totalTaxAmount / 100, label: '总含税金额', icon: incomeAmount },
        { data: this.list.item.completeWriteOffAmount / 100, label: '已核销金额', icon: transactionNumber },
        { data: this.list.item.unWriteOffAmount / 100, label: '待核销金额', icon: flowNumber },
        { data: setVerificationState(this.list.item.writeOffStatus), label: '核销状态', icon: chargeOffStatus }
      ];
    }
  },
  created() {
    this.id = this.$route.params.id || '';
    this.fetchData();
    this.getPaySelect();
  },
  methods: {
    hasRouteAuth,
    clientStatusFilter,
    moneyFilter,
    bigDataFilter,
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.filterInput));
      paramsRangeFormat(this.rangeKeyArr, params);
      this.listLoading = true;
      getChargeReportList(this.id, this.page, this.perPage, params).then(({ data }) => {
        this.list = data;
        this.ids = '';
        this.list.isInit = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    async getPaySelect() {
      try {
        const result = await getPayOption();
        if (result.code === 200) {
          const options = result.data.map(item => {
            return {
              value: item.id,
              label: item.name
            };
          });
          const newFilterItem = {
            keyword: 'payMethod', name: '付款方式', type: 'select', labelWidth: '85px',
            options: [{ value: -1, label: '全部' }, ...options]
          };
          this.$set(this.filterList, 6, newFilterItem);
        }
      } catch (error) {
        console.log(error);
      }
    },
    queryEmpty() {
      this.filterInput = {};
      this.queryClick();
    },
    queryClick() {
      this.fetchData(true);
    },
    enterSuccess() {
      this.$emit('getDetail');
      this.queryClick();
    },
    toCancel(scope) {
      this.$confirm('确定撤销核销？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        this.listLoading = true;
        this.cancelLoading = true;
        getRepealWriteOff(scope.row.id, 1).then(res => {
          this.listLoading = false;
          this.cancelLoading = false;
          this.fetchData();
          this.$emit('getDetail');
        }).catch(() => {
          this.cancelLoading = false;
          this.listLoading = false;
        });
      });
    },
    addDrawerOpen() {
      this.$refs['writeOfFinancialFlowRef'].initData(this.list.item.unWriteOffAmount, this.detailData);
    },
    getPayWay(row) {
      const clientType = this.clientStatusFilter(row.clientType);
      return row.paymentMethod ? clientType + ' / ' + row.paymentMethod : clientType;
    },
    toFinanceDetail(row) {
      const url = this.$router.resolve({
        name: 'chargeOffDetail',
        params: { chargeOffId: row.financeTxnId }
      });
      window.open(url.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.submit-btn {
  // margin-top: 17px;
  height: 32px;
  position: absolute;
  right: 0;
  top: 0;
}
.display-flex {
  display: flex;
  .flex-1 {
    flex: 1;
  }
  .submit-btn {
    left: 50px !important;
    right: auto;
  }
}
.middle-box {
  // text-align: right;
  margin-bottom: 12px;
  margin-top: 12px;
}
.amount-info {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  background:#FAFAFC;
  padding: 0px 10px 10px 10px;
  margin-top: 4px;
}
.amount-info-item {
  display: flex;
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  flex-basis: 23%;
  margin-right: 10px;
  position: relative;
  border-right: 1px solid #DDE1EA;
  &:last-child {
    margin-right: 0 !important;
    border-right: none;
  }
  .icon  {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
  .label {
    font-size:14px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:#999;
    font-weight: 500;
    line-height:14px;
    margin-right: 5px;
  }
  .amount {
    font-size:16px;
    font-family: DIN Alternate;
    font-weight: bold;
    line-height: 20px;
    color: #5F77C3;
  }
  .content {
    color: #406EFF;
    font-size: 16px;
    font-weight: bold;
  }
  &:last-child {
    margin-right: 0;
  }
}
.to-cancel {
  color: #515151;
  border: 1px solid #e4e4e4;
  &:hover {
    color: #406EFF;
  }
}
.to-cancel.is-disabled {
  color: #e0e0e0;
}
.light-word {
  color: #406eff;
  cursor: pointer;
}
</style>
